/*
 * @Author: szx
 * @Date: 2021-11-17 12:05:16
 * @LastEditTime: 2021-11-17 13:14:25
 * @Description:
 * @FilePath: \leetcode\300-399\318\318.js
 */

/**
 * @param {string[]} words
 * @return {number}
 */
// var maxProduct = function (words) {
//     words.sort((a, b) => a.length - b.length);
//     let l = words.length - 2,
//         r = words.length - 1;
//     let res = 0;
//     while (l >= 0 && r > l) {
//         if (isUnique(words[l], words[r])) {
//             if (res < words[l].length * words[r].length) {
//                 res = words[l].length * words[r].length;
//             }
//         }
//         if (l == 0 && r >= 1) {
//             r--;
//             l = r - 1;
//         } else {
//             l--;
//         }
//     }
//     return res;
// };

var maxProduct = function (words) {
    let res = 0;
    const n = words.length;
    for (let i = 0; i < n; i++) {
        for (let j = i; j < n; j++) {
            if (isUnique(words[i], words[j]) && res < words[i].length * words[j].length) {
                res = words[i].length * words[j].length;
            }
        }
    }
    return res;
};

const isUnique = function (a, b) {
    const num_a = 'a'.charCodeAt();
    const res = new Array(26).fill(0);

    for (const i of a) {
        res[i.charCodeAt() - num_a]++;
    }
    for (const j of b) {
        res[j.charCodeAt() - num_a]--;
    }
    let sum = 0;
    for (const r of res) {
        sum += Math.abs(r);
    }
    if (sum != a.length + b.length) {
        return false;
    }
    return true;
};
console.log(maxProduct(['a', 'aa', 'aaa', 'aaaa']));
